﻿#include <wx/app.h>
#include <wx/wx.h>

#pragma warning(disable:4996)

#include "SP.h"
#include "SPGameRoot.h"

class SPGApp : public wxApp
{
public:
	virtual bool OnInit();
};

class SPGFrame: public wxFrame
{
public:
	SPGFrame(wxFrame *frame, const wxString& title);
	~SPGFrame();
private:
	enum
	{
		idTimer = 0
	};
	void OnPaint( wxPaintEvent& evt );
	void OnSize( wxSizeEvent& evt );
	void OnTimer( wxTimerEvent& evt ); 

	wxTimer m_Timer;

	HANDLE m_hThread;

	DECLARE_EVENT_TABLE()
};

// Function for counting secord
DWORD WINAPI OnFrame(LPVOID p)
{
	while( SPGGetRoot()->IsFrameFinish() )
	{
		SPGGetRoot()->OnFrame();
	}

	return 0;
}

IMPLEMENT_APP(SPGApp);

bool SPGApp::OnInit()
{

	SPGFrame* frame = new SPGFrame(0L, _("SPGame"));
	frame->Show();
	return true;
}

BEGIN_EVENT_TABLE( SPGFrame, wxFrame )
	EVT_PAINT( SPGFrame::OnPaint )
	EVT_SIZE( SPGFrame::OnSize )
	EVT_TIMER( idTimer, SPGFrame::OnTimer )
END_EVENT_TABLE()

SPGFrame::SPGFrame(wxFrame *frame, const wxString& title)
	: wxFrame(frame, -1, title, wxDefaultPosition, wxSize(1100,700)),
	m_Timer( this, idTimer )
{
	HWND hWnd = GetHandle();
	UINT width = GetClientRect().GetWidth();
	UINT height = GetClientRect().GetHeight();
	SPGGetRoot()->Create( hWnd, width, height );

	m_hThread = CreateThread(NULL,0,OnFrame,NULL,0,NULL);
	//m_Timer.Start( 18 );
}

SPGFrame::~SPGFrame()
{
	while ( SPGGetRoot()->IsFrameFinish() )
	{
		TerminateThread( m_hThread, 0 );
		CloseHandle( m_hThread );
	}
}

void SPGFrame::OnSize( wxSizeEvent& evt )
{
	wxSize newSize = evt.GetSize();
	UINT width = wxMax( 1, newSize.GetWidth() );
	UINT height = wxMax( 1, newSize.GetHeight() );

	SPGGetRoot()->SetSize( width, height );
}

void SPGFrame::OnPaint( wxPaintEvent& evt )
{
	if ( SPGGetRoot()->IsFrameFinish() )
		SPGGetRoot()->OnFrame();
	evt.Skip();
}

void SPGFrame::OnTimer( wxTimerEvent& evt )
{
	//SPGGetRoot()->OnFrame();
}


